package com.atguigu.chapter07.D04_State;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Author: Pepsi
 * Date: 2023/8/9
 * Desc:
 */
public class Flink07_State_Key_Aggregate {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        env
                .socketTextStream("hadoop101", 9999) // socket只能是1
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                .keyBy(WaterSensor::getId)
                // 键控状态必须在keyBy后使用
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {


                    private AggregatingState<WaterSensor, Double> avgVcState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        avgVcState = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<WaterSensor, Avg, Double>(
                                "avgVcState",
                                new AggregateFunction<WaterSensor, Avg, Double>() {
                                    @Override
                                    public Avg createAccumulator() {
                                        return new Avg();
                                    }

                                    @Override
                                    public Avg add(WaterSensor value, Avg acc) {
                                        acc.sum += value.getVc();
                                        acc.count++;
                                        return acc;
                                    }

                                    @Override
                                    public Double getResult(Avg acc) {
                                        return acc.avg();
                                    }

                                    @Override
                                    public Avg merge(Avg a, Avg b) {
                                        return null;
                                    }
                                },
                                Avg.class
                        ));
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        avgVcState.add(value);

                        out.collect(ctx.getCurrentKey()+" 的平均水位："+avgVcState.get());
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class Avg {
        public Integer sum = 0;
        public Long count = 0L;

        public Double avg(){
            return sum *1.0 / count;
        }
    }
}